package com.supplychain.financial.parent.common.net;

import javax.net.ssl.HttpsURLConnection;
import java.io.*;
import java.net.*;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;


/**
 * @Copyright 2016 Drgon。LT
 * @类的作用：HTTP客户端连接工具
 * @author huangqianhai@combinedpay.com
 * @创建时间:2016年8月10日下午3:37:38
 * @版本号:1.0
 * @修改人:
 * @修改时间:
 */
public class HttpClient {
	private URL url;
	private int connectionTimeout;
	private int readTimeOut;
	private String result;

	public String getResult() {
		return this.result;
	}

	public void setResult(String result) {
		this.result = result;
	}

	public HttpClient(String url, int connectionTimeout, int readTimeOut) {
		try {
			this.url = new URL(url);
			this.connectionTimeout = connectionTimeout;
			this.readTimeOut = readTimeOut;
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}
	}

	public int send(Map<String, String> data, String encoding) throws Exception {
		HttpURLConnection httpURLConnection;
		try {
			httpURLConnection = createConnection(encoding);
			if (null == httpURLConnection)
				throw new Exception("创建连接失败");
			requestServer(httpURLConnection, getRequestParamString(data, encoding), encoding);
			this.result = response(httpURLConnection, encoding);
			return httpURLConnection.getResponseCode();
		} catch (Exception e) {
			throw e;
		}
	}

	private void requestServer(URLConnection connection, String message, String encoder) throws Exception {
		PrintStream out = null;
		try {
			connection.connect(); 
			out = new PrintStream(connection.getOutputStream(), false, encoder);
			out.print(message);
			out.flush();
		} catch (Exception e) {
		} finally {
			if (null != out)
				out.close();
		}
	}

	private String response(HttpURLConnection connection, String encoding) throws URISyntaxException, IOException, Exception {
		InputStream in = null;
		StringBuilder sb = new StringBuilder(1024);
		BufferedReader br = null;
		String temp = null;
		try {
			in = connection.getInputStream();
			br = new BufferedReader(new InputStreamReader(in, encoding));
			while (null != (temp = br.readLine()))
				sb.append(temp);
			return sb.toString();
		} catch (Exception e) {
		} finally {
			if (null != br)
				br.close();
			if (null != in)
				in.close();
			if (null != connection)
				connection.disconnect();
		}
		return null;
	}

	private HttpURLConnection createConnection(String encoding) throws ProtocolException {
		HttpURLConnection httpURLConnection = null;
		try {
			httpURLConnection = (HttpURLConnection) this.url.openConnection();
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
		httpURLConnection.setConnectTimeout(this.connectionTimeout);
		httpURLConnection.setReadTimeout(this.readTimeOut);
		httpURLConnection.setDoInput(true);
		httpURLConnection.setDoOutput(true);
		httpURLConnection.setUseCaches(false);
		httpURLConnection.setRequestProperty("Content-type",new StringBuilder().append("application/x-www-form-urlencoded;charset=").append(encoding).toString());
		httpURLConnection.setRequestMethod("POST");
		if ("https".equalsIgnoreCase(this.url.getProtocol())) {
			HttpsURLConnection husn = (HttpsURLConnection) httpURLConnection;
			husn.setSSLSocketFactory(new BaseHttpSSLSocketFactory());
			husn.setHostnameVerifier(new BaseHttpSSLSocketFactory.TrustAnyHostnameVerifier());
			return husn;
		}
		return httpURLConnection;
	}

	private String getRequestParamString(Map<String, String> requestParam, String coder) {
		if ((null == coder) || ("".equals(coder)))
			coder = "UTF-8";
		StringBuffer sb = new StringBuffer("");
		String result = "";
		if ((null != requestParam) && (0 != requestParam.size())) {
			for (Iterator i$ = requestParam.entrySet().iterator(); i$.hasNext();) {
				Map.Entry en = (Map.Entry) i$.next();
				try {
					sb.append(new StringBuilder()
							.append((String) en.getKey()).append("=")
							.append(((null == en.getValue()) || ("".equals(en.getValue()))) ? "" : URLEncoder.encode((String) en.getValue(), coder))
							.append("&").toString());
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
					return "";
				}
			}
			result = sb.substring(0, sb.length() - 1);
		}
		return result;
	}
	
	/**
	 * 客户端连接测试
	 * @param args
	 * @throws Exception
	 */
	public static void main(String[] args)  throws Exception{
		String encoding = "UTF-8";
	    String url = "http://127.0.0.1:8080/clouderp-sys-rest/api/login/mobile/sendSMS";
	    String result = "";
		HttpClient hc = new HttpClient(url, 5000, 5000);
		Map data = new HashMap(); 
	    data.put("version", "3.0.0");
	    try {
	      int status = hc.send(data, encoding);
	      if (200 == status)
	        result = hc.getResult();
	    }
	    catch (Exception e) {
	      e.printStackTrace();
	    }  
	}
}
